using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class AbilityListDisplay : MonoBehaviour {
	
	public GameObject itemDisplayTemplate;
	public GameObject marker;
	
	List<GameObject> itemDisplays;
	
	public UITable table;
	
	public bool forFeats;
	
	public bool toggled = false;
	
	Ability selectedAbility;
	
	GameObject replacementChoiceWindow;

	// Use this for initialization
	void Start () {
		
		itemDisplayTemplate.SetActiveRecursively(false);
		marker.SetActiveRecursively(false);
		
		itemDisplays = new List<GameObject>();
		
		UIButtonMessage message = gameObject.AddComponent<UIButtonMessage>();
		message.target = gameObject;
		message.functionName = "ToggleAbilityDisplays";
		
		table.repositionNow = true;
	}
	
	// Update is called once per frame
	void Update () {
	
	}
	
	public void ToggleAbilityDisplays()
	{
		if(!toggled)
		{
			marker.SetActiveRecursively(true);
			
			itemDisplayTemplate.SetActiveRecursively(true);
			
			List<Ability> sortedList;
			
			if(forFeats)
				sortedList = SheetManager.activeCharacter.Feats;
			else
				sortedList = SheetManager.activeCharacter.specialAbility;
			
			sortedList.Sort((w1,w2) => w1.name.CompareTo(w2.name));
			
			GameObject go = new GameObject();
			go.transform.parent = transform.parent;
			go.transform.localPosition = Vector3.zero;
			go.transform.localScale = Vector3.one;
			go.name = itemDisplayTemplate.name;
			itemDisplays.Add(go);
			
			string addButtonLabel = "Add ";
			if(forFeats)
				addButtonLabel += "Feat  (" + SheetManager.activeCharacter.featsUsed + "/" + SheetManager.activeCharacter.totalFeats + " Feats)";
			else
				addButtonLabel += "Special Ability";
			
			go = NGUITools.AddButton(go, 24, addButtonLabel);
			UIButtonMessage message = go.AddComponent<UIButtonMessage>();
			message.target = gameObject;
			message.functionName = "AddToAbilityList";
			go.transform.localPosition = Vector3.right * ((BoxCollider)go.collider).size.x/2;
			
			foreach(Ability ability in sortedList )
			{
				go = Instantiate(itemDisplayTemplate) as GameObject;
				go.transform.parent = transform.parent;
				go.transform.localPosition = itemDisplayTemplate.transform.localPosition;
				go.transform.localScale = itemDisplayTemplate.transform.localScale;
				go.name += ability.name;
				
				if(!(SheetManager.activeCharacter.addedFeats.Contains(ability) || SheetManager.activeCharacter.addedSpecialAbilities.Contains(ability)))
				{
					go.name = go.name.Replace("g_","i_");
					go.name = go.name.Replace("l_","n_");
				}
				
				AbilityListDisplayTemplate template = go.GetComponent<AbilityListDisplayTemplate>();
				template.isFeat = forFeats;
				
				template.OriginalName.text = "";
				
				if(ability.replacementAbility)
				{
					Ability currentAbility = ability.selectedReplacement;
					template.OriginalName.text += ability.name;
					template.AbilityName.text = "Click to Select Replacement.";
					bool abilityTester = true;
					
					while(abilityTester && currentAbility != null)
					{
						if(currentAbility.replacementAbility)
						{
							template.OriginalName.text += ": " + currentAbility.name;
							currentAbility = currentAbility.selectedReplacement;
						}
						else
						{
							template.AbilityName.text = currentAbility.name;
							abilityTester = false;
						}
					}
				}
				else
				{
					template.AbilityName.text = ability.name;
					template.OriginalName.text = "";
				}
				
				template.ability = ability;
				
				message = go.AddComponent<UIButtonMessage>();
				message.target = gameObject;
				message.functionName = "DisplayOptions";
				
				itemDisplays.Add(go);
			}
			
			itemDisplayTemplate.SetActiveRecursively(false); 
			
			table.repositionNow = true;
			toggled = true;
		}
		else
		{
			marker.SetActiveRecursively(false);
			foreach(GameObject go in itemDisplays)
			{
				Destroy(go);
			}
			itemDisplays.Clear();
			table.repositionNow = true;
			toggled = false;
		}
	}
	
	IEnumerator RemoveAbility()
	{
		List<bool> outBools = new List<bool>{false};
		
		yield return StartCoroutine(HelperFunctions.ConfirmationWindow("Are you sure you want to remove " + selectedAbility.name + " from your character sheet?", outBools));
		
		if(outBools[0])
		{
			if(forFeats)
				SheetManager.activeCharacter.addedFeats.Remove(selectedAbility);
			else
				SheetManager.activeCharacter.addedSpecialAbilities.Remove(selectedAbility);
			
			ToggleAbilityDisplays();
			ToggleAbilityDisplays();
			
			SheetManager.SaveActiveCharacter(false);
		}
	}
	
	IEnumerator AddToAbilityList()
	{
		if(forFeats)
		{
			bool doIt = true;
					
			if(SheetManager.activeCharacter.featsUsed >= SheetManager.activeCharacter.totalFeats)
			{
				List<bool> output = new List<bool>{false};
				yield return StartCoroutine(HelperFunctions.ConfirmationWindow("You are not legally allowed another feat. Continue anyway?", output));
				
				if(!output[0])
					doIt = false;
			}
			
			if(doIt)
				BrowserManager.CreateAbilityBrowser(gameObject, "AddAbility", new List<string>(), true, false);
		}
		else
			BrowserManager.CreateAbilityBrowser(gameObject, "AddAbility", new List<string>(), false, true);
		
		yield break;
	}
	
	void AddAbility(List<string> addedAbilities)
	{
		foreach(string an in addedAbilities)
		{	
			if(forFeats)
			{
				Ability f = FeatManager.Load(an);
				if(f != null)
				{
					bool doIt = true;
					
					if(doIt)
					{
						SheetManager.activeCharacter.addedFeats.Add(f);
						
						SheetManager.activeCharacter.AddNewBuffs(f.buffs);
					}
				}
			}
			else
			{
				Ability sa = SpecialAbilityManager.Load(an);
				if(sa != null)
				{
					SheetManager.activeCharacter.addedSpecialAbilities.Add(sa);
					SheetManager.activeCharacter.AddNewBuffs(sa.buffs);
				}
			}
		}
		
		SheetManager.SaveActiveCharacter(false);
		
		ToggleAbilityDisplays();
		ToggleAbilityDisplays();
	}
	
	IEnumerator DisplayOptions(GameObject target)
	{
		selectedAbility = target.GetComponent<AbilityListDisplayTemplate>().ability;
		
		List<string> options = new List<string>{"View Info"};
		
		if(selectedAbility.replacementAbility)
		{
			bool testSelectAbility = false;
			bool testLooper = true;
			
			Ability currentAbility = selectedAbility.selectedReplacement;
			while(testLooper)
			{
				if(currentAbility != null)
				{
					if(currentAbility.replacementAbility)
						currentAbility = currentAbility.selectedReplacement;
					else
					{
						testSelectAbility = true;
						testLooper = false;
					}
				}
				else
					testLooper = false;
			}
			
			if(!testSelectAbility)
			{
				options.Add("Select Replacement");
			}
			else
			{
				options.Add("Remove Replacement");
				options.Add("Replacement Info");
			}
		}
		
		if((SheetManager.activeCharacter.addedFeats.Contains(selectedAbility) 
			|| SheetManager.activeCharacter.addedSpecialAbilities.Contains(selectedAbility)))
		{
			options.Add("Remove");
		}
		
		if(options.Count == 1)
		{
			AbilityInfo();
			return false;
		}
		
		List<SetterWindowDescription> descVar = new List<SetterWindowDescription>
		{
			new SetterWindowDescription("", "Action", false, options)
		};
		
		yield return StartCoroutine(HelperFunctions.SetterWindow("Options", descVar));
		
		switch(descVar[0].outVariable)
		{
			case "View Info":
				AbilityInfo();
				break;
			case "Remove":
				StartCoroutine(RemoveAbility());
				break;
			case "Select Replacement":
				StartCoroutine(SelectReplacement());
				break;
			case "Remove Replacement":
				StartCoroutine(RemoveReplacement());
				break;
			case "Replacement Info":
				StartCoroutine(ReplacementInfo());
				break;
		}
	}
	
	IEnumerator SelectReplacement()
	{
		List<string> options;
		
		Ability looperAbility = selectedAbility;
		bool looperTest = true;
		
		while(looperTest)
		{
			if(looperAbility.selectedReplacement != null)
			{
				if(looperAbility.selectedReplacement.replacementAbility)
					looperAbility = looperAbility.selectedReplacement;
				else
					looperTest = false;
			}
			else
			{
				looperTest = false;
			}
		}
		
		options = looperAbility.replacementList;
		
		selectedAbility = looperAbility;
		
		BrowserManager.CreateAbilitySubsetBrowser(gameObject, "SelectReplacementChoice", looperAbility.replacementList);
	
		yield break;
	}
	
	void SelectReplacementChoice(List<string> choices)
	{
		if(choices == null || choices.Count < 1)
			return;
		
		string choice = choices[0];
		
		if(FeatManager.index.ContainsKey(choice))
			selectedAbility.selectedReplacement = FeatManager.Load(choice);
		else
			selectedAbility.selectedReplacement = SpecialAbilityManager.Load(choice);
		
		SheetManager.SaveActiveCharacter(false);
		
		//Destroy(replacementChoiceWindow);
	
		ToggleAbilityDisplays();
		ToggleAbilityDisplays();
	}
	
	IEnumerator RemoveReplacement()
	{
		if(selectedAbility.replacementAbility && selectedAbility.selectedReplacement != null)
		{
			List<bool> outBools = new List<bool>{false};
		
			yield return StartCoroutine(HelperFunctions.ConfirmationWindow("Are you sure you want to remove the current replacement ability for " + selectedAbility.name + "?", outBools));
			
			if(outBools[0])
			{
				selectedAbility.selectedReplacement = null;
				
				SheetManager.SaveActiveCharacter(false);
		
				ToggleAbilityDisplays();
				ToggleAbilityDisplays();
			}
		}
		yield break;
	}
	
	IEnumerator ReplacementInfo()
	{
		Ability replacementAbility = selectedAbility.selectedReplacement;
		bool looperTest = true;
		while(looperTest)
		{
			if(replacementAbility.replacementAbility && replacementAbility.selectedReplacement != null)
			{
				replacementAbility = replacementAbility.selectedReplacement;
			}
			else
				looperTest = false;
		}
		
		if(replacementAbility != null)
		{
			selectedAbility = replacementAbility;
			AbilityInfo();
		}
		yield break;
	}
	
	void AbilityInfo()
	{
		GameObject g = Instantiate(GameReference.reference.NewAbilityWindowPrefab) as GameObject;
		g.transform.parent = GameReference.reference.BaseMenuPanel;
		g.transform.localScale = Vector3.one;
		BrowserManager.currentNewTransform = g.transform;
		g.transform.localPosition = BrowserManager.CurrentIndex;
		
		CreateAbilityWindow a = g.GetComponent<CreateAbilityWindow>();
		a.target = gameObject;
		a.functionName = "Do Nothing";
		a.LoadAbilityDisplay(selectedAbility.name, forFeats, true);
	}
}
